﻿//Transaction.cpp
#include"Transaction.hh"
#include<sstream>
#include<iomanip>
#ifdef _WIN32
#include<Windows.h>
#endif
namespace Banking {

    int Transaction::nextTransactionId = 1;  //初始化静态成员变量

    //交易类的构造函数实现
    Transaction::Transaction(const std::string& source, const std::string& target,
        double amount, TransactionType type, const std::string& note)
        : transactionId(nextTransactionId++),
        sourceAccountId(source),
        targetAccountId(target),
        amount(amount),
        type(type),
        note(note),
        timestamp(std::chrono::system_clock::now())
    {
    }

    //获取交易信息的字符串表示形式的实现
    std::string Transaction::toString() const {
        SetConsoleOutputCP(CP_UTF8);//Windows系统下设置控制台输出为UTF-8编码
        std::stringstream ss;
        auto time = std::chrono::system_clock::to_time_t(timestamp);
        char timeBuffer[26];  //定义一个足够大的缓冲区来存储时间字符串
        errno_t err = ctime_s(timeBuffer, sizeof(timeBuffer), &time);
        //格式化输出交易信息
        ss << "Transaction ID: T" << std::setfill('0') << std::setw(3) << transactionId << "\n"
            << "Type: ";

        switch (type) {
        case TransactionType::DEPOSIT:
            ss << "Deposit";
            break;
        case TransactionType::WITHDRAWAL:
            ss << "Withdrawal";
            break;
        case TransactionType::TRANSFER:
            ss << "Transfer";
            break;
        }

        ss << "\n"
            << "Source Account: " << sourceAccountId << "\n";

        if (!targetAccountId.empty()) {
            ss << "Target Account: " << targetAccountId << "\n";
        }

        if (err == 0) {
            ss << "Amount: ¥" << std::fixed << std::setprecision(2) << amount << "\n"
                << "Time: " << timeBuffer;
        }
        else {
            ss << "Amount: ¥" << std::fixed << std::setprecision(2) << amount << "\n"
                << "Time: Error getting time\n";
        }

        if (!note.empty()) {
            ss << "Note: " << note << "\n";
        }

        return ss.str();
    }

} //namespace Banking